using CsvHelper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Experimental.GlobalIllumination;

public class DatasetLoader : MonoBehaviour
{
    public class DataField
    {
        public float x { get; set; }
        
        public float y { get; set; }

        public float z { get; set; }
    }

    [SerializeField]
    public UnityEvent<string, List<DataField>> onDataLoaded;
    public UnityEvent<string> onDataLoadedFailed;

    bool m_isLoaded = false;
    bool m_isLoadFailed = false;
    List<DataField> m_records;
    string m_fileName;
    string m_failedInfo;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (m_isLoaded)
        {
            onDataLoaded.Invoke(m_fileName, m_records);
            m_isLoaded = false;
        }
        if (m_isLoadFailed)
        {
            onDataLoadedFailed.Invoke(m_failedInfo);
            m_isLoadFailed = false;
        }
    }

    public void LoadData(string filePath)
    {
        FileInfo info = new(filePath);

        if (!info.Exists)
        {
            m_isLoadFailed = true;
            m_failedInfo = string.Format("'{0}' Does Not Exsit", info.Name);
            return;
        }

        using var reader = new StreamReader(filePath);
        using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
        try
        {
            m_records = csv.GetRecords<DataField>().ToList();
            m_fileName = info.Name;
            m_isLoaded = true;
        }
        catch (Exception)
        {
            m_isLoadFailed = true;
            m_failedInfo = string.Format("'{0}' Loading Failed", info.Name);
            return;
        }

    }
}
